/**
 * Created by   : HuXiaoting
 * Created time : 2017/3/21
 * File explain : 材料-登录页面交互JS文件
 */
require.config({
  baseUrl: "../../libs",
  paths: {
    pubconfig:['../matersellercenter'],
    jquery: ["jquery/jquery-1.11.3"],
    comConfig: ["../common/js/common-config"],
    layer: ["layer/layer"],
    static: ["//static.geetest.com/static/tools/gt"],
    vue: ["//cdn.bootcss.com/vue/2.3.3/vue"]
  }
});
require(["jquery","pubconfig"], function () {
  sessionStorage.setItem('matersellercenter',JSON.stringify(pubconfig));
  require(["vue", "comConfig", "layer", "static"], operationCodeFun);
});

function operationCodeFun(Vue){
  // 由于使用require框架整合，我们需要为layer.js配置读取css文件的路径
  layer.config({
    path: "../../libs/layer/"
  });
  // 配置文件内容
  var QHConfig = $("body").data("config");

  //变量声明
  var oTelNumber = $("#telNumber");
  var oPassword = $("#password");
  var keyWord = null;//获取ajax的head验证码参数


  getKeyWordByServer();


  var userNameReg = QHConfig.testReg.phoneReg;
  var passWordReg = /^[0-9A-Za-z]{6,20}$/;//6到20位数字字母组合

  var tips = [
    "您输入的密码与手机号不匹配，请重新输入",
    "验证失败",
    "您的账号已被禁用，如有问题请拨打：400-820-8820",
    "请输入用户名",
    "密码不能为空",
    "密码不正确",
    "您输入的手机号有误，请重新输入"
  ];

  var loginMain = new Vue({
    el: "#login-main",
    data: {
      userName: "",
      passWord: "",
      canClick: false,
      tip: "",
      err: false
    },
    methods: {
      login: function () {
        var userInfo = null;//登录需要的用户信息
        $(".login-tip").addClass("hide");//每次点击都隐藏当前提示再判断

        //判断验证码
        if (keyWord == null) {
          this.tip = "请先完成滑块验证";
          this.err = true;
          return;
        }else {
          this.err =false;
        }

        //手机用户信息
        userInfo = {
          geetestChallenge: keyWord.challenge,
          geetestValidate: keyWord.validate,
          geetestSeccode: keyWord.seccode
        };

        userInfo = JSON.stringify(userInfo);

        this.getAjaxFun(userInfo);//登录请求
      },
      userNameTest: function () {
        var test = false;
        if (this.userName.length === 0) {
          this.tip = tips[3];
          this.err = true;
        } else {
          if (userNameReg.test(this.userName) == false) {
            this.tip = tips[6];
            this.err = true;
          } else {
            this.tip = "";
            this.err = false;
            test = true;
          }
        }
        return test;
      },
      passwordTest: function () {
        if (this.passWord.length === 0) {
          this.tip = tips[4];
          this.err = true;
        } else {
          if (passWordReg.test(this.passWord) == false) {
            this.tip = tips[5];
            this.err = true;
          } else {
            this.tip = "";
            this.err = false;
          }
        }
      },
      iptKeyup: function () {
        userNameReg.test(this.userName) && passWordReg.test(this.passWord)
          ? (this.canClick = true) : (this.canClick = false);
      },
      //调用登录ajax
      getAjaxFun: function (ajaxData) {
        var login = this;
        $.ajax(tokenAjax({
          type: "get",
          url: QHConfig.url.login + "/" + login.userName + "/" + login.passWord,
          data: ajaxData,
          dataType: "json",
          success: function (data) {
            if (data.status == 200) {
              $(".login-tip").addClass("hide");
              //判断是不是有storage功能
              if (typeof(Storage) !== "undefined") {
                sessionStorage.setItem('materToken', data.data);
                window.location.href = "../../index.html";
              } else {
                console.log("抱歉！您的浏览器不支持 Web Storage");
              }
            } else if (data.status == '400') {
              login.tip = data.message;
              login.err = true;
            }
          },
          error: function () {
            layer.msg("网络不稳定");
          }
        }));
      }
    }
  });


  //向服务器获取验证码
  function getKeyWordByServer() {
    var nowTime = (new Date()).getTime();//获取当前时间戳

    // 验证开始需要向网站主后台获取id，challenge，success（是否启用failback）
    $.ajax(tokenAjax({
      url: QHConfig.url.loginCode + nowTime, // 加随机数防止缓存
      type: "get",
      async: false,
      dataType: "json",
      success: function (data) {
        data = JSON.parse(data.data);
        // 使用initGeetest接口
        // 参数1：配置参数
        // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
        initGeetest({
          gt: data.gt,
          challenge: data.challenge,
          product: "float", // 产品形式，包括：float，embed，popup。注意只对PC版验证码有效
          offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
          // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
        }, handlerPopup);
      }
    }));
  };

  //获取验证码成功回调
  function handlerPopup(captchaObj) {
    // 成功的回调
    captchaObj.onSuccess(function () {
      var validate = captchaObj.getValidate();//方法

      keyWord = {
        challenge: validate.geetest_challenge,
        validate: validate.geetest_validate,
        seccode: validate.geetest_seccode
      };//获取登录ajax的head参数

      userNameReg.test(loginMain.userName) && passWordReg.test(loginMain.passWord)
        ? (loginMain.canClick = true) : (loginMain.canClick = false);

    });
    // 将验证码加到id为popup-captcha的元素里
    captchaObj.appendTo("#popup-captcha");
  }
}
